﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using System.Linq;
using ConsolidationTool.Common;
using ConsolidationTool.WebParts.ControlTemplates;
using ConsolidationTool.Common.Entities;
using System.Web;
using System.Web.Script.Serialization;
using System.IO;

namespace ConsolidationTool.WebParts.Layouts.CReport.Actual
{
    public partial class DillReport : FSReportBase
    {

        public relaClass Relationships = new relaClass();
        public List<ListIns> TableData = new List<ListIns>();
        public string ListTitle;
        public override ControlTemplates.CommonEntitySelector TopSelector
        {
            get
            {
                return commonEntitySelector as ControlTemplates.CommonEntitySelector;
            }
        }

        public override void BeforLoad()
        {

            //TopSelector.EntitySelectorChanged += new CommonEntitySelector.EntitySelectorChangeHandler(TopSelector_EntitySelectorChanged);
            ListTitle = HttpUtility.UrlDecode(Request["t"]);
            string templateName = HttpUtility.UrlDecode(Request["template"]);
            templateName = templateName.IsNullOrEmpty() ? ListTitle : templateName;

            title.Text = ListTitle;

            Relationships = new JavaScriptSerializer().Deserialize<List<relaClass>>(GetFieldTemplate()).FirstOrDefault(p => p.Title == templateName);
            Relationships = Relationships == null ? new relaClass() : Relationships;


            if (!IsPostBack && !Automatic)
                loadConfigYearMonth();

            InitBaseInfo();
        }

        string GetFieldTemplate()
        {
            string temp = string.Empty;
            using (StreamReader sr = new StreamReader(Server.MapPath("FieldTemplate.js")))
            {
                temp = sr.ReadToEnd();
            }
            return temp;
        }

        void InitBaseInfo()
        {

            Title_HRM1.Text = TopSelector.yearTextBox.Text + ".01";
            Title_HRM2.Text = TopSelector.yearTextBox.Text + ".02";
            Title_HRM3.Text = TopSelector.yearTextBox.Text + ".03";
            Title_HRM4.Text = TopSelector.yearTextBox.Text + ".04";
            Title_HRM5.Text = TopSelector.yearTextBox.Text + ".05";
            Title_HRM6.Text = TopSelector.yearTextBox.Text + ".06";
            Title_HRM7.Text = TopSelector.yearTextBox.Text + ".07";
            Title_HRM8.Text = TopSelector.yearTextBox.Text + ".08";
            Title_HRM9.Text = TopSelector.yearTextBox.Text + ".09";
            Title_HRM10.Text = TopSelector.yearTextBox.Text + ".10";
            Title_HRM11.Text = TopSelector.yearTextBox.Text + ".11";
            Title_HRM12.Text = TopSelector.yearTextBox.Text + ".12";
        }

        private void loadConfigYearMonth()
        {
            TopSelector.yearTextBox.Text = Common.BusinessService.GetConfiguration(Constants.Flash_Input_Year);
            TopSelector.monthTextBox.Text = Common.BusinessService.GetConfiguration(Constants.Flash_Input_Month);
        }
        public override void GenerateReport_Click(object sender, EventArgs e)
        {
            //邦定current月数据
            int m = Convert.ToInt32(TopSelector.monthTextBox.Text);

            for (int i = 1; i <= m; i++)
            {
                BindLastMonth(TopSelector.lbCoCd.Text, TopSelector.yearTextBox.Text, i.ToString());
            }
            reportData.DataSource = TableData;
            reportData.DataBind();
        }

        public void BindLastMonth(string coCd, string year, string month)
        {
            string y = year;
            string m = (Convert.ToInt32(month)).ToString();
            SPListItem it = Common.BusinessService.GetItem(coCd, y, m, ListTitle);
            var SubRowData = Common.BusinessService.GetSubItems(coCd, year, month, "Sub " + ListTitle, "*");
            var CacheSPItems = new List<SPListItem>();
            if (SubRowData != null)
                CacheSPItems = SubRowData.Cast<SPListItem>().ToList();

            if (it != null)
            {
                string currency = it["Currency"] + "";
                // var allCM = it.ContentType.Fields.OfType<SPField>().Where(p => p.StaticName.StartsWith("CM_"));
                Relationships.Fields.Where(field => !string.IsNullOrEmpty(field.ac) || field.empty).ToList().ForEach(relaItem =>
                {
                    bool fieldExist = true;
                    relaItem.ac = relaItem.ac.Replace(" ", "");
                    var ins = TableData.FirstOrDefault(a => a.AccountCode == relaItem.ac);
                    if (ins == null)
                    {
                        fieldExist = false;
                        ins = new ListIns();
                        ins.AccountCode = relaItem.ac;
                        ins.Description = relaItem.desc;
                        ins.Unit = string.IsNullOrEmpty(relaItem.unit) ? currency : Utility.UnitPlaceholderComplie(relaItem.unit, commonEntitySelector);
                        ins.Type = "";
                    }
                    if (!relaItem.empty && StartWithProfix(relaItem.ac))
                    {
                        string field = string.IsNullOrEmpty(relaItem.field) ? "CM_" + relaItem.ac : relaItem.field;
                        string fieldValue = it[field] + "";
                        //decimal numValue = 0;
                        //numValue = decimal.TryParse(fieldValue, out numValue) ? numValue : 0;
                        //fieldValue = string.Format("{0:N0}", numValue);

                        //if (fieldValue.IndexOf('.') != -1)
                        //{
                        //    string left = decimal.Parse(fieldValue.Split('.')[0]).ToString("N0");
                        //    fieldValue = left + "." + fieldValue.Split('.')[1];
                        //}
                        //else
                        //    fieldValue = decimal.Parse(fieldValue).ToString("N0");


                        var monthPro = ins.GetType().GetProperty("Month" + month);
                        monthPro.SetValue(ins, fieldValue, null);

                        if (!fieldExist)
                        {
                            ins.Description = string.IsNullOrEmpty(relaItem.desc) ? ins.Description : relaItem.desc;

                            if (relaItem.bold)
                                ins.Description = string.Format("<strong>{0}</strong>", ins.Description);

                            TableData.Add(ins);
                        }
                    }
                    else
                    {
                        if (month == "1")
                        {
                            var empty = new ListIns();
                            if (!string.IsNullOrEmpty(relaItem.ac) && relaItem.ac.ToUpper() != "CONTROL")
                                empty.AccountCode = relaItem.ac;
                            TableData.Add(empty);
                        }
                    }

                    //process subrow data

                    if (relaItem.hasSubrow)
                    {

                        CacheSPItems.ForEach(item =>
                        {
                            var subUniconCode = item["LM_AccountCode"] + "";
                            if (subUniconCode.Trim() == relaItem.ac.Trim())
                            {
                                ins = TableData.FirstOrDefault(a => a.ParentAccountCode == relaItem.ac && a.RGC == item["CoName"] + "");
                                if (ins == null)
                                {
                                    fieldExist = false;
                                    ins = new ListIns();
                                    ins.ParentAccountCode = relaItem.ac;
                                    ins.Description = item["CoName"] + "";
                                    ins.Unit = string.IsNullOrEmpty(relaItem.unit) ? currency : Utility.UnitPlaceholderComplie(relaItem.unit, commonEntitySelector);
                                    ins.Type = "";
                                }

                                string field = string.IsNullOrEmpty(relaItem.field) ? "CM_" + relaItem.ac : relaItem.field;
                                string fieldValue = it[field] + "";

                                var monthPro = ins.GetType().GetProperty("Month" + month);
                                monthPro.SetValue(ins, fieldValue, null);

                                if (!fieldExist)
                                    TableData.Add(ins);
                            }
                        });

                    }

                });
            }

        }

        private bool StartWithProfix(string a)
        {
            foreach (var item in Relationships.Profix)
            {
                if (a.StartsWith(item))
                    return true;
            }
            return false;
        }
    }
}
